<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      inline
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item prop="params.type">
        <el-select
          v-model="queryParams.params.type"
          placeholder="请选择统计类型"
          @change="dateTypeChange"
        >
          <el-option
            v-for="item in countList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="params.startTime">
        <el-date-picker
          v-model="queryParams.params.startTime"
          value-format="yyyy-MM-dd"
          :type="dataType"
          placeholder="开始日期"
          @change="timeChange"
        />
      </el-form-item>
      <el-form-item prop="params.endTime">
        <el-date-picker
          v-model="queryParams.params.endTime"
          value-format="yyyy-MM-dd"
          :type="dataType"
          placeholder="结束日期"
          @change="timeChange"
        />
      </el-form-item>
      <el-form-item prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          查询
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    <el-button size="mini" type="primary" @click="openContract"> 创建合同 </el-button>
    <el-row :gutter="10">
      <p>
        成交金额：¥ {{ orderTotalList.totalAmount }}元，成交订单：{{
          orderTotalList.transactionOrderNum
        }}，成交产品数量：{{ orderTotalList.transactionNum }}，平均客单价：¥
        {{ orderTotalList.avgAmount }}元
      </p>
    </el-row>
    <el-table :data="dataList" v-loading="loading" border>
      <el-table-column label="费用编号" align="center" prop="sn" />
      <el-table-column label="费用类型" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.shoppingCarEnums | ctCostType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联客户" align="center" prop="createBy" />
      <el-table-column label="费用金额(元)" align="center" prop="updatePrice" />
      <!-- <el-table-column label="优惠折扣" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.discount ? scope.row.discount + "折" : "无" }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="发生时间" align="center" prop="createTime" />
      <el-table-column label="合同状态" align="center">
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.orderStatus != 'IN_PROGRESS' && scope.row.orderStatus != 'FAIL'
            "
            >{{ scope.row.contractStatus | ctContractStatus }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="开票状态" align="center">
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.orderStatus != 'IN_PROGRESS' && scope.row.orderStatus != 'FAIL'
            "
            >{{ scope.row.invoicing | ctInvoiceStatus }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="负责人员" align="center" prop="updateBy" />
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.params.pageNum"
      :limit.sync="queryParams.params.pageSize"
      @pagination="getList"
    />

    <el-dialog title="添加合同" :visible.sync="contractShow" width="500px" :close-on-click-modal="false" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联客户" prop="userId">
          <el-select
            v-model="form.userId"
            filterable
            placeholder="选择客户"
            @change="queryOrder"
          >
            <el-option
              v-for="item in personList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合同类型" prop="feesType">
          <el-select v-model="form.feesType" placeholder="选择类型" @change="queryOrder">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderItemIds">
          <el-select
            v-model="form.orderItemIds"
            multiple
            placeholder="请选择订单编号"
            @change="changePrice"
          >
            <el-option
              v-for="item in orderList"
              :key="item.orderItemId"
              :label="item.sn"
              :value="item.orderItemId"
            >
              <span>{{ item.sn }}</span>
              <span style="color: #c0c0c0">({{ item.updatePrice || 0 }}元)</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同金额" prop="money">
          <el-input placeholder="选择订单后自动计算" v-model="form.money" disabled>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="合同日期" prop="contractDate">
          <el-date-picker
            v-model="form.contractDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
            v-model="form.remark"
            :maxlength="300"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="attachment">
          <File-upload
            v-model="form.attachment"
            :fileType="['doc', 'xls', 'ppt', 'txt', 'pdf', 'png', 'jpg', 'jpeg']"
            label="点击上传合同附件"
            :isShowTip="false"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  orderTotal,
  addContract,
  getMemberList,
} from "@/api/financialManagement/orderManagement";

export default {
  data() {
    return {
      //合同类型
      typeList: [
        { value: "CLOUD_SERVER", label: "云服务器" },
        { value: "CLOUD_MARKET", label: "云市场" },
        { value: "GOV_CLOUD", label: "政务云" },
        { value: "CLOUD_SERVER_RENEW", label: "云服务器续费" },
        { value: "CLOUD_SERVER_CHANGE", label: "云服务器变更" },
      ],
      // 统计类型
      countList: [
        { value: "month", label: "按月统计" },
        { value: "season", label: "按季统计" },
        { value: "year", label: "按年统计" },
        { value: "day", label: "按日统计" },
      ],
      personList: [], // 关联客户
      orderList: [], // 订单列表
      orderTotalList: {
        totalAmount: "", //成交金额
        transactionOrderNum: "", //成交订单
        transactionNum: "", //成交产品数量
        avgAmount: "", //平均客单价
      },
      contractShow: false, //创建合同弹出框
      dataType: "month", //日期选择的类型
      loading: false, // 遮罩层
      showSearch: true, // 显示搜索条件
      total: 0, // 总条数
      dataList: [], // 订单管理表格数据
      // 查询参数
      queryParams: {
        createBy: "", //客户名称
        params: {
          type: "", //按月统计下拉框的值
          pageNum: 1,
          pageSize: 10,
          startTime: null, //开始时间
          endTime: null, //结束时间
        },
      },
      form: {}, //表单
      rules: {
        //表单验证
        userId: [{ required: true, message: "请选择客户", trigger: "blur" }],
        feesType: [{ required: true, message: "请选择合同类型", trigger: "blur" }],
        orderItemIds: [{ required: true, message: "请输入订单编号", trigger: "blur" }],
        contractDate: [{ required: true, message: "请选择日期", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
    this.getOrderTotal();
  },
  methods: {
    /**切换时间选择器的类型 */
    dateTypeChange(e) {
      if (e === "month") {
        this.dataType = "month";
      } else if (e === "year") {
        this.dataType = "year";
      } else if (e === "day") {
        this.dataType = "date";
      } else if (e === "season") {
        this.dataType = "month";
      }
    },
    // 时间选择改变
    timeChange(e) {
      if (e == "" || e == null) {
        this.queryParams.params.startTime = "";
        this.queryParams.params.endTime = "";
        return;
      }
      let date = new Date(e);
      if (this.queryParams.params.type == "season") {
        let y = date.getFullYear();
        let m = date.getMonth();
        if (m >= 0 && m <= 2) {
          this.queryParams.params.startTime = y + "-01-01";
          this.queryParams.params.endTime = y + "-03-31";
        } else if (m >= 3 && m <= 5) {
          this.queryParams.params.startTime = y + "-04-01";
          this.queryParams.params.endTime = y + "-06-30";
        } else if (m >= 6 && m <= 8) {
          this.queryParams.params.startTime = y + "-07-01";
          this.queryParams.params.endTime = y + "-09-30";
        } else if (m >= 9 && m <= 11) {
          this.queryParams.params.startTime = y + "-10-01";
          this.queryParams.params.endTime = y + "-12-31";
        }
      }
    },
    /**成交总结数据获取 */
    getOrderTotal() {
      orderTotal(this.queryParams).then((res) => {
        if (res.code === 200) {
          this.orderTotalList = res.data;
        }
      });
    },
    /** 查询合同订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams)
        .then((res) => {
          this.dataList = res.rows;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getOrderTotal();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        feesType: null,
        orderItemIds: [],
        contractDate: null,
        money: null,
        remark: null,
        attachment: null,
        attachment: null,
      };
      this.resetForm("form");
    },
    // 打开弹窗
    openContract() {
      this.reset();
      this.getMember();
      this.contractShow = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let data = Object.assign({}, this.form);
          console.log(data, "xxxxxxxx");
          addContract(data).then((res) => {
            this.$message.success("合同创建成功！");
            this.contractShow = false;
          });
        }
      });
    },
    // 查询客户订单
    queryOrder() {
      const { userId, feesType: type } = this.form;
      if (userId && type) {
        let data = {
          userId,
          contractStatus: 2,
          orderStatus: "SUCCESS",
          type,
          params: {
            pageNum: 1,
            pageSize: 1000,
          },
        };
        listOrder(data).then((res) => {
          this.orderList = res.rows;
        });
      } else {
        this.orderList = [];
      }
    },
    // 计算价格
    changePrice(e) {
      let money = 0;
      e.forEach((item) => {
        let row = this.orderList.find((i) => i.orderItemId == item);
        if (row) {
          money += row.updatePrice;
        }
      });
      this.form.money = money;
    },
    // 取消按钮
    cancel() {
      this.contractShow = false;
      this.reset();
    },
    // 获取客户列表
    getMember() {
      getMemberList().then((res) => {
        this.personList = res.data;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.el-select {
  width: 100%;
}
</style>
